package cn.whdream.datastructure.sort;
/**
 * 
 * @author admin
 * 从小到大，每一次都会把相对大的排到这一轮循环的数的最后一位  eg: 第一轮{3,9,-1,10,-2}->{3 -1 9 -2 10} 第二轮  {3 -1 9 -2 10}——>{-1 3 -2 9 10 }
 * 从大到小，把最小的往最后面怼
 * 1） 一共进行i-次大循环
 * 2） 次数会逐渐减少
 */
public class BubbleSortDemo {
	private static int[] numbers = {1,2,3,4};//{9,3,-1,10,-2};
	private static int[] numbers1 = {1,2,3,4}; //{9,3,-1,10,-2};
	public static void main(String[] args) {
		sortA(numbers);
		System.out.println("sort b............");
		sortB();	
	}
	private static void sortA(int[] mumberList) {
		int temp;
		for (int i = 0; i < mumberList.length-1; i++) {
			System.out.println("第"+i+"轮");
			//简单的优化，每一次，都提取出来 本轮最大的数据后，下一次就可以不再比较该数字，故直接 -i；
			for (int j = 0; j < mumberList.length-1-i; j++) {
				//print();
				int a = mumberList[j];
				int b = mumberList[j+1];
				System.out.printf("a = %d b = %d length = %d  \n\n",a,b,numbers.length-1-i);
				if(a > b) {
					mumberList[j] = b;
					mumberList[j+1] = a;
				}
			}
			print();
		}
	}
	/**
	 * 优化次数
	 */
	private static void sortB() {
		int temp;
		for (int i = 0; i < numbers1.length-1; i++) {
			System.out.println("第"+i+"轮");
			boolean finshed = true; 
			//简单的优化，每一次，都提取出来 本轮最大的数据后，下一次就可以不再比较该数字，故直接 -i；
			for (int j = 0; j < numbers1.length-1-i; j++) {
				//print();
				int a = numbers1[j];
				int b = numbers1[j+1];
				System.out.printf("a = %d b = %d length = %d  \n\n",a,b,numbers1.length-1-i);
				if(a > b) {
					numbers1[j] = b;
					numbers1[j+1] = a;
					finshed = false;
				}
			
			}
			if (finshed) {
				break;
			}
			print1();
		}
	}
	private static void print() {
		for (int i = 0; i < numbers.length; i++) {
			System.out.print(numbers[i]+" ");
		}
		System.out.println();
	}
	private static void print1() {
		for (int i = 0; i < numbers.length; i++) {
			System.out.print(numbers1[i]+" ");
		}
		System.out.println();
	}
}


